﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace 软构大作业
{
    public partial class Form15 : Form
    {
        private new AutoAdaptWindowsSize AutoSize;
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }
        private Data data = new Data();
        private DataTable dtBooks = new DataTable();
        public Form15()
        {
            InitializeComponent();
            InitializeBookListPanel();
            dgvBooks.CellDoubleClick += new DataGridViewCellEventHandler(dgvBooks_CellDoubleClick); // 添加双击事件
                                                                                                    // 设置窗体的KeyPreview属性为true，以便窗体可以接收键盘事件
            this.KeyPreview = true;
            // 为窗体添加KeyDown事件处理
            this.KeyDown += Form15_KeyDown;
        }

        private void dgvBooks_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0) // 确保双击的是有效行
            {
                // 获取选中的行
                DataGridViewRow row = dgvBooks.Rows[e.RowIndex];

                int bookId = Convert.ToInt32(row.Cells["book_id"].Value);

                // 创建并显示图书详情窗体，传递图书 ID
                Form18 form18 = new Form18();
                form18.BookId = bookId; // 假设 Form18 有一个属性 BookId 来接收图书 ID
                form18.ShowDialog();
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadBooksData();
        }

        private void Form15_Load(object sender, EventArgs e)
        {
            InitializeBookListPanel();
            LoadBooksData();
            AutoSize = new AutoAdaptWindowsSize(this);
            this.SizeChanged += new EventHandler(Form_SizeChanged);
        }
        private void Form_SizeChanged(object sender, EventArgs e)
        {//窗体大小改变事件
            if (AutoSize != null) // 一定加这个判断，电脑缩放布局不是100%的时候，会报错
            {
                AutoSize.FormSizeChanged();
            }
        }

        // 图书列表区布局
        private void InitializeBookListPanel()
        {
            // 图书列表（使用DataGridView）
            dgvBooks.AllowUserToAddRows = false;
            dgvBooks.AllowUserToDeleteRows = false;
            dgvBooks.ReadOnly = true;
            dgvBooks.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvBooks.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            //dgvBooks.Dock = DockStyle.Fill;

            // 初始列（后续动态生成）
            dgvBooks.Columns.Clear();

            // 设置列样式
            dgvBooks.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
        }

        private void LoadBooksData()
        {
            string sql = "SELECT * FROM library_db.books";
            string orderBy = GetOrderByClause();

            if (!string.IsNullOrEmpty(orderBy))
            {
                sql += " ORDER BY " + orderBy;
            }

            try
            {
                using (SqlDataReader reader = data.command(sql).ExecuteReader())
                {
                    dtBooks.Clear();
                    dtBooks.Load(reader);
                    dgvBooks.DataSource = dtBooks;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载图书数据时出错: " + ex.Message);
            }
        }

        private string GetOrderByClause()
        {
            string orderBy = "";
            switch (comboBox1.SelectedItem?.ToString())
            {
                case "按书名排序":
                    orderBy = "title";
                    break;
                case "按借阅量排序":
                    orderBy = "borrow_count";
                    break;
            }
            return orderBy;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            Global.Instance.form15login.Hide();
            Global.Instance.form8login.Show();
        }

        private void Form15_FormClosed(object sender, FormClosedEventArgs e)
        {
            textBox1.Text = "";
            Global.Instance.form15login=null;
            Global.Instance.form8login.Show();
        }
        private void Form15_KeyDown(object sender, KeyEventArgs e)
        {
            // 检查是否按下Enter键
            if (e.KeyCode == Keys.Enter)
            {
                // 触发button1的点击事件
                button1.PerformClick();
                // 标记事件已处理，防止其他控件处理该事件
                e.Handled = true;
                e.SuppressKeyPress = true; // 防止发出"叮"的声音
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string searchKeyword = textBox1.Text.Trim(); // 获取搜索关键字（去空格）
            if (string.IsNullOrEmpty(searchKeyword))
            {
                MessageBox.Show("请输入书名/作者/分类");
                LoadBooksData();
            }
            SearchBooks(searchKeyword); // 执行搜索
        }

        private void SearchBooks(string keyword)
        {
            // 搜索最简单的实现：在书名、作者、分类中模糊搜索
            string sql = "SELECT * FROM library_db.books WHERE title LIKE @Keyword OR author LIKE @Keyword OR category LIKE @Keyword";

            try
            {
                using (SqlConnection connection = new SqlConnection("Server=localhost;Database=library_2;Trusted_Connection=true"))
                {
                    connection.Open();
                    using (SqlCommand command = new SqlCommand(sql, connection))
                    {
                        // 添加参数
                        command.Parameters.AddWithValue("@Keyword", $"%{keyword}%");

                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            dtBooks.Clear();
                            dtBooks.Load(reader);
                            dgvBooks.DataSource = dtBooks;

                            if (dtBooks.Rows.Count == 0)
                            {
                                MessageBox.Show("未搜索到相关书籍");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("搜索图书时出错: " + ex.Message);
            }
        }

    }
}
